<template>
  <div class="ansible-audit-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="audit-content">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1 class="page-title">
              <i class="fa fa-network-wired"></i>
              Docker网络管理
            </h1>
            <p class="page-subtitle">管理Docker网络配置和连接</p>
          </div>
          <div class="stats-section">
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.total_networks || 0 }}</div>
              <div class="stat-label">网络总数</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.custom_networks || 0 }}</div>
              <div class="stat-label">自定义网络</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.connected_containers || 0 }}</div>
              <div class="stat-label">已连接容器</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="search-filters glass-effect">
        <el-form inline class="search-form">
          <el-form-item>
            <el-select v-model="selectedServer" placeholder="选择Docker服务器" class="server-select" @change="onServerChange">
              <el-option
                v-for="server in dockerServers"
                :key="server.id"
                :label="server.name"
                :value="server.id"
              />
            </el-select>
            <el-button type="primary" @click="refreshNetworks" class="glass-button refresh-button" :loading="loading">
              <i class="fa fa-refresh"></i>
              刷新网络
            </el-button>
            <el-button @click="createNetwork" class="glass-button add-button">
              <i class="fa fa-plus"></i>
              创建网络
            </el-button>
            <el-button @click="pruneNetworks" class="glass-button delete-button">
              <i class="fa fa-trash"></i>
              清理未使用网络
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 网络列表 -->
      <div class="audit-table-section glass-effect">
        <div class="section-title">
          <i class="fa fa-network-wired"></i>
          Docker网络列表
        </div>

        <el-table
          :data="networks"
          style="width: 100%"
          v-loading="loading"
          row-class-name="audit-row"
          class="audit-table"
        >
          <el-table-column prop="Name" label="网络名称" min-width="150">
            <template #default="scope">
              <div class="config-name">
                <i class="fa fa-network-wired"></i>
                {{ scope.row.Name }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="Driver" label="驱动" width="100">
            <template #default="scope">
              <span class="network-driver" :class="scope.row.Driver">
                {{ scope.row.Driver }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="Scope" label="作用域" width="100" />

          <el-table-column label="子网" width="150">
            <template #default="scope">
              <span class="subnet-text">
                {{ getSubnet(scope.row) || '无' }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="网关" width="150">
            <template #default="scope">
              <span class="gateway-text">
                {{ getGateway(scope.row) || '无' }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="连接容器数" width="120">
            <template #default="scope">
              <el-tag type="info" size="small">
                {{ scope.row.Containers ? Object.keys(scope.row.Containers).length : 0 }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="330" :show-overflow-tooltip="false">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  @click="viewDetails(scope.row)"
                  size="small"
                  class="glass-button import-button"
                >
                  <i class="fa fa-search"></i>
                  详情
                </el-button>
                <el-button
                  @click="viewConnectedContainers(scope.row)"
                  size="small"
                  class="glass-button sync-button network-connect-btn"
                >
                  <i class="fa fa-link"></i>
                  连接容器
                </el-button>
                <el-button
                  v-if="!scope.row.is_system"
                  @click="deleteNetwork(scope.row)"
                  size="small"
                  class="glass-button delete-button"
                >
                  <i class="fa fa-trash"></i>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>

  <!-- 创建网络对话框 -->
  <el-dialog
    v-model="createDialogVisible"
    title="创建Docker网络"
    width="600px"
    class="glass-dialog"
    :close-on-click-modal="false"
  >
    <el-form :model="createForm" label-width="100px">
      <el-form-item label="网络名称" required>
        <el-input v-model="createForm.name" placeholder="请输入网络名称" class="glass-input" />
      </el-form-item>

      <el-form-item label="驱动类型">
        <el-select v-model="createForm.driver" class="glass-select" style="width: 100%" @change="onDriverChange">
          <el-option label="bridge - 桥接网络（默认）" value="bridge" />
          <el-option label="host - 主机网络" value="host" />
          <el-option label="none - 无网络" value="none" />
          <el-option label="overlay - 跨主机网络（Swarm）" value="overlay" />
          <el-option label="macvlan - MAC地址网络" value="macvlan" />
          <el-option label="ipvlan - IP网络" value="ipvlan" />
          <el-option label="container - 容器网络" value="container" />
        </el-select>
      </el-form-item>

      <!-- bridge 驱动配置 -->
      <template v-if="createForm.driver === 'bridge'">
        <el-form-item label="子网">
          <el-input v-model="createForm.subnet" placeholder="例如: 172.20.0.0/16" class="glass-input" />
        </el-form-item>

        <el-form-item label="网关">
          <el-input v-model="createForm.gateway" placeholder="例如: 172.20.0.1" class="glass-input" />
        </el-form-item>

        <el-form-item label="IP范围">
          <el-input v-model="createForm.ip_range" placeholder="例如: 172.20.240.0/20" class="glass-input" />
        </el-form-item>
      </template>

      <!-- container 驱动配置 -->
      <template v-if="createForm.driver === 'container'">
        <el-form-item label="容器名称/ID" required>
          <el-input v-model="createForm.container" placeholder="输入要共享网络的容器名称或ID" class="glass-input" />
        </el-form-item>
      </template>

      <!-- macvlan 驱动配置 -->
      <template v-if="createForm.driver === 'macvlan'">
        <el-form-item label="父接口" required>
          <el-input v-model="createForm.parent" placeholder="例如: eth0" class="glass-input" />
        </el-form-item>

        <el-form-item label="子网">
          <el-input v-model="createForm.subnet" placeholder="例如: 192.168.1.0/24" class="glass-input" />
        </el-form-item>

        <el-form-item label="网关">
          <el-input v-model="createForm.gateway" placeholder="例如: 192.168.1.1" class="glass-input" />
        </el-form-item>
      </template>

      <!-- ipvlan 驱动配置 -->
      <template v-if="createForm.driver === 'ipvlan'">
        <el-form-item label="父接口" required>
          <el-input v-model="createForm.parent" placeholder="例如: eth0" class="glass-input" />
        </el-form-item>

        <el-form-item label="IPVLAN模式">
          <el-select v-model="createForm.ipvlan_mode" class="glass-select" style="width: 100%">
            <el-option label="l2 - 二层模式" value="l2" />
            <el-option label="l3 - 三层模式" value="l3" />
          </el-select>
        </el-form-item>

        <el-form-item label="子网">
          <el-input v-model="createForm.subnet" placeholder="例如: 192.168.1.0/24" class="glass-input" />
        </el-form-item>

        <el-form-item label="网关">
          <el-input v-model="createForm.gateway" placeholder="例如: 192.168.1.1" class="glass-input" />
        </el-form-item>
      </template>

      <!-- overlay 驱动配置 -->
      <template v-if="createForm.driver === 'overlay'">
        <el-form-item label="子网">
          <el-input v-model="createForm.subnet" placeholder="例如: 10.0.0.0/24" class="glass-input" />
        </el-form-item>

        <el-form-item label="网关">
          <el-input v-model="createForm.gateway" placeholder="例如: 10.0.0.1" class="glass-input" />
        </el-form-item>

        <el-form-item label="加密">
          <el-switch v-model="createForm.encrypted" />
        </el-form-item>
      </template>

      <!-- host 和 none 驱动不需要额外配置 -->
      <template v-if="createForm.driver === 'host'">
        <div class="driver-info-box info-type">
          <i class="fa fa-info-circle"></i>
          <div class="info-content">
            <div class="info-title">主机网络模式</div>
            <div class="info-desc">容器将直接使用主机的网络栈，不需要额外配置。</div>
          </div>
        </div>
      </template>

      <template v-if="createForm.driver === 'none'">
        <div class="driver-info-box warning-type">
          <i class="fa fa-exclamation-triangle"></i>
          <div class="info-content">
            <div class="info-title">无网络模式</div>
            <div class="info-desc">容器将没有网络连接，不需要额外配置。</div>
          </div>
        </div>
      </template>

      <el-form-item label="标签">
        <div v-for="(label, index) in createForm.labels" :key="index" class="label-item">
          <el-input v-model="label.key" placeholder="键" class="glass-input label-key" />
          <el-input v-model="label.value" placeholder="值" class="glass-input label-value" />
          <el-button @click="removeLabel(index)" class="glass-button delete-button" size="small" :disabled="createForm.labels.length === 1">
            <i class="fa fa-minus"></i>
          </el-button>
        </div>
        <el-button @click="addLabel" class="glass-button add-button" size="small">
          <i class="fa fa-plus"></i>
          添加标签
        </el-button>
      </el-form-item>

      <el-form-item label="选项">
        <div v-for="(option, index) in createForm.options" :key="index" class="label-item">
          <el-input v-model="option.key" placeholder="键" class="glass-input label-key" />
          <el-input v-model="option.value" placeholder="值" class="glass-input label-value" />
          <el-button @click="removeOption(index)" class="glass-button delete-button" size="small" :disabled="createForm.options.length === 1">
            <i class="fa fa-minus"></i>
          </el-button>
        </div>
        <el-button @click="addOption" class="glass-button add-button" size="small">
          <i class="fa fa-plus"></i>
          添加选项
        </el-button>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="createDialogVisible = false" class="glass-button">
          <i class="fa fa-times"></i>
          取消
        </el-button>
        <el-button @click="submitCreateNetwork" class="glass-button add-button" :loading="loading">
          <i class="fa fa-plus"></i>
          创建网络
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 网络详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    :title="detailDialogTitle"
    width="90%"
    top="5vh"
    class="glass-dialog inspect-dialog"
    destroy-on-close
  >
    <template #header="{ titleId, titleClass }">
      <div class="inspect-header">
        <div class="inspect-title">
          <i class="fa fa-info-circle inspect-icon"></i>
          <span :id="titleId" :class="titleClass">{{ detailDialogTitle }}</span>
        </div>
        <div class="inspect-controls">
          <el-button @click="refreshNetworkDetail" size="small" class="glass-button">
            <i class="fa fa-refresh"></i>
            刷新
          </el-button>
          <el-button @click="copyNetworkDetail" class="glass-button">
            <i class="fa fa-copy"></i>
            复制
          </el-button>
          <el-button @click="scrollDetailToTop" class="glass-button">
            <i class="fa fa-arrow-up"></i>
            顶部
          </el-button>
          <el-button @click="scrollDetailToBottom" class="glass-button">
            <i class="fa fa-arrow-down"></i>
            底部
          </el-button>
          <el-button @click="closeDetailDialog" class="glass-button danger">
            <i class="fa fa-times"></i>
            关闭
          </el-button>
        </div>
      </div>
    </template>
    <div class="inspect-content" ref="detailContentRef">
      <pre class="inspect-pre">{{ networkDetailContent }}</pre>
    </div>
  </el-dialog>

  <!-- 连接容器对话框 -->
  <el-dialog
    v-model="containersDialogVisible"
    title="连接的容器"
    width="1200px"
    class="glass-dialog"
    :close-on-click-modal="false"
  >
    <el-table :data="currentNetworkContainers" class="audit-table">
      <el-table-column prop="name" label="容器名称" min-width="200">
        <template #default="scope">
          <div class="config-name">
            <i class="fa fa-cube"></i>
            {{ scope.row.name }}
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="id" label="容器ID" width="150">
        <template #default="scope">
          <span class="container-id">{{ scope.row.id.substring(0, 12) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="ipv4Address" label="IPv4地址" width="180" />

      <el-table-column prop="macAddress" label="MAC地址" width="180">
        <template #default="scope">
          <span class="mac-address">{{ scope.row.macAddress }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="endpointId" label="端点ID" width="150">
        <template #default="scope">
          <span class="endpoint-id">{{ scope.row.endpointId.substring(0, 12) }}</span>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// 响应式数据
const loading = ref(false)
const selectedServer = ref('')

// 统计数据
const statistics = reactive({
  total_networks: 0,
  custom_networks: 0,
  connected_containers: 0
})

// 数据列表
const dockerServers = ref([])
const networks = ref([])

// 页面加载
onMounted(() => {
  loadData()
})

// 监听服务器选择变化
const onServerChange = async () => {
  if (selectedServer.value) {
    // 清空之前的数据
    networks.value = []
    Object.assign(statistics, {
      total_networks: 0,
      custom_networks: 0,
      connected_containers: 0
    })

    loading.value = true
    try {
      // 加载网络列表（会自动计算统计数据）
      await loadNetworks()
    } catch (error) {
      console.error('切换服务器失败:', error)
      ElMessage.error('切换服务器失败')
    } finally {
      loading.value = false
    }
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 先加载服务器列表
    await loadDockerServers()
    // 然后加载网络列表（会自动计算统计数据）
    if (selectedServer.value) {
      await loadNetworks()
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载Docker服务器列表
const loadDockerServers = async () => {
  try {
    const { dockerServerAPI } = await import('@/api/docker')
    const response = await dockerServerAPI.getServers()
    dockerServers.value = response.data.results || response.data || []

    // 自动选择第一个服务器
    if (dockerServers.value.length > 0 && !selectedServer.value) {
      selectedServer.value = dockerServers.value[0].id
    }
  } catch (error) {
    console.error('加载Docker服务器失败:', error)
    ElMessage.error('加载Docker服务器失败')
  }
}

// 加载网络列表
const loadNetworks = async () => {
  if (!selectedServer.value) return

  try {
    const { dockerNetworkAPI } = await import('@/api/docker')
    const response = await dockerNetworkAPI.getNetworks(selectedServer.value)
    if (response.data.success) {
      networks.value = response.data.networks
      // 网络列表加载完成后立即计算统计数据
      loadStatistics()
    }
  } catch (error) {
    console.error('加载网络列表失败:', error)
    ElMessage.error('加载网络列表失败')
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    // 基于网络列表计算统计数据
    const totalNetworks = networks.value.length
    const customNetworks = networks.value.filter(n =>
      !['bridge', 'host', 'none'].includes(n.Name)
    ).length

    // 计算连接的容器数量
    let connectedContainers = 0
    networks.value.forEach(network => {
      if (network.Containers) {
        connectedContainers += Object.keys(network.Containers).length
      }
    })

    Object.assign(statistics, {
      total_networks: totalNetworks,
      custom_networks: customNetworks,
      connected_containers: connectedContainers
    })
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 刷新网络列表
const refreshNetworks = () => {
  loadData()
  ElMessage.success('网络列表已刷新')
}

// 创建网络相关变量
const createDialogVisible = ref(false)
const createForm = reactive({
  name: '',
  driver: 'bridge',
  subnet: '',
  gateway: '',
  ip_range: '',
  container: '',        // container驱动需要
  parent: '',          // macvlan/ipvlan驱动需要
  ipvlan_mode: 'l2',   // ipvlan驱动需要
  encrypted: false,    // overlay驱动需要
  labels: [{ key: '', value: '' }],
  options: [{ key: '', value: '' }]
})

// 驱动切换处理
const onDriverChange = () => {
  // 清空相关字段
  createForm.subnet = ''
  createForm.gateway = ''
  createForm.ip_range = ''
  createForm.container = ''
  createForm.parent = ''
  createForm.ipvlan_mode = 'l2'
  createForm.encrypted = false
}

// 网络操作
const createNetwork = () => {
  if (!selectedServer.value) {
    ElMessage.warning('请先选择Docker服务器')
    return
  }
  createDialogVisible.value = true
}

// 提交创建网络
const submitCreateNetwork = async () => {
  if (!createForm.name) {
    ElMessage.warning('网络名称不能为空')
    return
  }

  // 根据驱动类型验证必填字段
  if (createForm.driver === 'container' && !createForm.container) {
    ElMessage.warning('Container驱动需要指定容器名称或ID')
    return
  }

  if ((createForm.driver === 'macvlan' || createForm.driver === 'ipvlan') && !createForm.parent) {
    ElMessage.warning(`${createForm.driver}驱动需要指定父接口`)
    return
  }

  try {
    loading.value = true
    const { dockerNetworkAPI } = await import('@/api/docker')

    // 处理标签和选项
    const labels = {}
    createForm.labels.forEach(label => {
      if (label.key && label.value) {
        labels[label.key] = label.value
      }
    })

    const options = {}
    createForm.options.forEach(option => {
      if (option.key && option.value) {
        options[option.key] = option.value
      }
    })

    // 根据驱动类型添加特定选项
    if (createForm.driver === 'container') {
      options['container'] = createForm.container
    } else if (createForm.driver === 'macvlan') {
      options['parent'] = createForm.parent
    } else if (createForm.driver === 'ipvlan') {
      options['parent'] = createForm.parent
      options['ipvlan_mode'] = createForm.ipvlan_mode
    } else if (createForm.driver === 'overlay' && createForm.encrypted) {
      options['encrypted'] = 'true'
    }

    const requestData = {
      name: createForm.name,
      driver: createForm.driver,
      labels,
      options
    }

    // 只有bridge、overlay、macvlan、ipvlan驱动才需要IPAM配置
    if (['bridge', 'overlay', 'macvlan', 'ipvlan'].includes(createForm.driver)) {
      if (createForm.subnet) requestData.subnet = createForm.subnet
      if (createForm.gateway) requestData.gateway = createForm.gateway
      if (createForm.ip_range) requestData.ip_range = createForm.ip_range
    }

    const response = await dockerNetworkAPI.createNetwork(selectedServer.value, requestData)

    if (response.data.success) {
      ElMessage.success('网络创建成功')
      createDialogVisible.value = false
      resetCreateForm()
      await loadData()
    } else {
      ElMessage.error(response.data.message || '创建网络失败')
    }
  } catch (error) {
    console.error('创建网络失败:', error)
    ElMessage.error('创建网络失败')
  } finally {
    loading.value = false
  }
}

// 重置创建表单
const resetCreateForm = () => {
  Object.assign(createForm, {
    name: '',
    driver: 'bridge',
    subnet: '',
    gateway: '',
    ip_range: '',
    container: '',
    parent: '',
    ipvlan_mode: 'l2',
    encrypted: false,
    labels: [{ key: '', value: '' }],
    options: [{ key: '', value: '' }]
  })
}

// 添加标签
const addLabel = () => {
  createForm.labels.push({ key: '', value: '' })
}

// 删除标签
const removeLabel = (index) => {
  if (createForm.labels.length > 1) {
    createForm.labels.splice(index, 1)
  }
}

// 添加选项
const addOption = () => {
  createForm.options.push({ key: '', value: '' })
}

// 删除选项
const removeOption = (index) => {
  if (createForm.options.length > 1) {
    createForm.options.splice(index, 1)
  }
}

// 提取子网信息
const getSubnet = (network) => {
  if (network.IPAM && network.IPAM.Config && network.IPAM.Config.length > 0) {
    return network.IPAM.Config[0].Subnet
  }
  return null
}

// 提取网关信息
const getGateway = (network) => {
  if (network.IPAM && network.IPAM.Config && network.IPAM.Config.length > 0) {
    return network.IPAM.Config[0].Gateway
  }
  return null
}

// 网络详情相关
const detailDialogVisible = ref(false)
const currentNetworkDetail = ref(null)
const detailDialogTitle = ref('')
const networkDetailContent = ref('')
const detailContentRef = ref()

const viewDetails = async (network) => {
  try {
    loading.value = true
    currentNetworkDetail.value = network
    detailDialogTitle.value = `网络 ${network.Name} 详细信息`
    networkDetailContent.value = '正在加载网络详细信息...'
    detailDialogVisible.value = true

    await refreshNetworkDetail()
  } catch (error) {
    console.error('获取网络详情失败:', error)
    ElMessage.error('获取网络详情失败')
  } finally {
    loading.value = false
  }
}

// 刷新网络详情
const refreshNetworkDetail = async () => {
  if (!currentNetworkDetail.value || !selectedServer.value) {
    return
  }

  try {
    const { dockerNetworkAPI } = await import('@/api/docker')
    const response = await dockerNetworkAPI.getNetworkDetails(selectedServer.value, currentNetworkDetail.value.Id)

    if (response.data.success) {
      networkDetailContent.value = JSON.stringify(response.data.network, null, 2)
    } else {
      networkDetailContent.value = `获取网络详细信息失败: ${response.data.message || '未知错误'}`
    }
  } catch (error) {
    console.error('刷新网络详情失败:', error)
    networkDetailContent.value = `获取网络详细信息失败: ${error.message}`
  }
}

// 复制网络详情
const copyNetworkDetail = async () => {
  try {
    await navigator.clipboard.writeText(networkDetailContent.value)
    ElMessage.success('网络详情已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 滚动到顶部
const scrollDetailToTop = () => {
  if (detailContentRef.value) {
    detailContentRef.value.scrollTop = 0
  }
}

// 滚动到底部
const scrollDetailToBottom = () => {
  if (detailContentRef.value) {
    detailContentRef.value.scrollTop = detailContentRef.value.scrollHeight
  }
}

// 关闭详情对话框
const closeDetailDialog = () => {
  networkDetailContent.value = ''
  currentNetworkDetail.value = null
  detailDialogVisible.value = false
}

// 连接容器相关
const containersDialogVisible = ref(false)
const currentNetworkContainers = ref([])

const viewConnectedContainers = (network) => {
  if (network.Containers && Object.keys(network.Containers).length > 0) {
    // 转换容器数据格式
    currentNetworkContainers.value = Object.entries(network.Containers).map(([containerId, containerInfo]) => ({
      id: containerId,
      name: containerInfo.Name,
      ipv4Address: containerInfo.IPv4Address,
      ipv6Address: containerInfo.IPv6Address,
      macAddress: containerInfo.MacAddress,
      endpointId: containerInfo.EndpointID
    }))
    containersDialogVisible.value = true
  } else {
    ElMessage.info('该网络没有连接的容器')
  }
}

const pruneNetworks = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清理所有未使用的网络吗？此操作不可恢复。',
      '确认清理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    // TODO: 实现API调用
    ElMessage.success('未使用网络清理完成')
    await loadNetworks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理网络失败:', error)
      ElMessage.error('清理失败')
    }
  }
}

const inspectNetwork = (network: any) => {
  ElMessage.info(`查看网络 ${network.name} 详情功能开发中...`)
}

const connectContainer = (network: any) => {
  ElMessage.info(`连接容器到网络 ${network.name} 功能开发中...`)
}

const deleteNetwork = async (network: any) => {
  // 检查是否为系统网络
  if (['bridge', 'host', 'none'].includes(network.Name)) {
    ElMessage.warning('系统网络不能删除')
    return
  }

  // 检查是否有容器连接
  const connectedContainers = network.Containers ? Object.keys(network.Containers).length : 0
  if (connectedContainers > 0) {
    ElMessage.warning(`网络 ${network.Name} 还有 ${connectedContainers} 个容器连接，无法删除`)
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除网络 "${network.Name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    loading.value = true
    const { dockerNetworkAPI } = await import('@/api/docker')
    const response = await dockerNetworkAPI.removeNetwork(selectedServer.value, network.Id)

    if (response.data.success) {
      ElMessage.success('网络删除成功')
      await loadData()
    } else {
      ElMessage.error(response.data.message || '删除网络失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除网络失败:', error)
      ElMessage.error('删除网络失败')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 使用与Zabbix服务器配置页面完全相同的样式 */
.ansible-audit-container {
  min-height: 100vh;
  background: linear-gradient(
    135deg,
    rgba(0, 0, 0, 0.9) 0%,
    rgba(20, 20, 40, 0.95) 50%,
    rgba(0, 0, 0, 0.9) 100%
  );
  overflow-x: hidden;
}

.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite linear;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 10px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 300px 200px;
  animation: zoom 40s infinite linear;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, rgba(255,255,255,0.5), transparent);
  background-repeat: repeat;
  background-size: 400px 300px;
  animation: zoom 60s infinite linear;
}

@keyframes zoom {
  from { transform: scale(1); }
  to { transform: scale(1.5); }
}

.audit-content {
  position: relative;
  z-index: 10;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.glass-effect {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(20px);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.page-header {
  margin-bottom: 30px;
  padding: 30px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
}

.title-section h1 {
  color: rgba(255, 255, 255, 0.95);
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.title-section h1 i {
  color: #a4f4ba;
  margin-right: 12px;
}

.page-subtitle {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  min-width: 120px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #a4f4ba;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.search-filters {
  margin-bottom: 30px;
  padding: 20px;
}

.search-form {
  margin: 0;
}

.audit-table-section {
  padding: 30px;
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.95);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.section-title i {
  color: #a4f4ba;
}

.config-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.config-name i {
  color: #00eaff;
}

.time-text, .subnet-text, .gateway-text {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
}

.subnet-text, .gateway-text {
  font-family: monospace;
}

.server-select {
  width: 200px;
  margin-right: 10px;
}

/* 工具栏按钮样式 - 完全照抄Zabbix服务器配置页面 */
.glass-button {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 8px !important;
  padding: 8px 16px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;

  &:hover {
    background: rgba(164, 244, 186, 0.25) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 16px rgba(164, 244, 186, 0.2) !important;
  }

  i {
    margin-right: 6px !important;
    color: #00eaff !important;
  }

  &.refresh-button {
    background: rgba(138, 43, 226, 0.2) !important;
    border-color: rgba(138, 43, 226, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(138, 43, 226, 0.3) !important;
      border-color: rgba(138, 43, 226, 0.6) !important;
      box-shadow: 0 4px 16px rgba(138, 43, 226, 0.3) !important;
    }

    i {
      color: #8a2be2 !important;
    }
  }

  &.sync-button {
    background: rgba(59, 130, 246, 0.2) !important;
    border-color: rgba(59, 130, 246, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(59, 130, 246, 0.3) !important;
      border-color: rgba(59, 130, 246, 0.6) !important;
      box-shadow: 0 4px 16px rgba(59, 130, 246, 0.3) !important;
    }

    i {
      color: #3b82f6 !important;
    }
  }

  &.add-button {
    background: rgba(34, 197, 94, 0.2) !important;
    border-color: rgba(34, 197, 94, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(34, 197, 94, 0.3) !important;
      border-color: rgba(34, 197, 94, 0.6) !important;
      box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
    }

    i {
      color: #22c55e !important;
    }
  }

  &.import-button {
    background: rgba(6, 182, 212, 0.2) !important;
    border-color: rgba(6, 182, 212, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(6, 182, 212, 0.3) !important;
      border-color: rgba(6, 182, 212, 0.6) !important;
      box-shadow: 0 4px 16px rgba(6, 182, 212, 0.3) !important;
    }

    i {
      color: #06b6d4 !important;
    }
  }

  &.delete-button {
    background: rgba(239, 68, 68, 0.2) !important;
    border-color: rgba(239, 68, 68, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(239, 68, 68, 0.3) !important;
      border-color: rgba(239, 68, 68, 0.6) !important;
      box-shadow: 0 4px 16px rgba(239, 68, 68, 0.3) !important;
    }

    i {
      color: #ef4444 !important;
    }
  }
}

/* 表格样式 */
:deep(.audit-table) {
  background: transparent !important;

  .el-table__header {
    background: rgba(164, 244, 186, 0.1) !important;
  }

  .el-table__header th {
    background: transparent !important;
    border-bottom: 1px solid rgba(164, 244, 186, 0.3) !important;
    color: rgba(255, 255, 255, 0.9) !important;
    font-weight: 600 !important;
  }

  .el-table__body tr {
    background: transparent !important;

    &:hover {
      background: rgba(164, 244, 186, 0.05) !important;
    }
  }

  .el-table__body td {
    border-bottom: 1px solid rgba(164, 244, 186, 0.1) !important;
    color: rgba(255, 255, 255, 0.8) !important;
  }
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: nowrap;
}

.action-buttons .glass-button {
  padding: 8px 12px !important;
  font-size: 12px;
  white-space: nowrap;
  width: auto !important;
  min-width: 70px;
}

.action-buttons .network-connect-btn {
  padding: 8px 10px !important;
  min-width: 80px;
}

.network-driver {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.network-driver.bridge {
  background: rgba(64, 158, 255, 0.2);
  color: #409eff;
}

.network-driver.host {
  background: rgba(103, 194, 58, 0.2);
  color: #67c23a;
}

.network-driver.overlay {
  background: rgba(230, 162, 60, 0.2);
  color: #e6a23c;
}

.network-driver.none {
  background: rgba(144, 147, 153, 0.2);
  color: #909399;
}

.network-driver.null {
  background: rgba(144, 147, 153, 0.2);
  color: #909399;
}

.network-driver.macvlan {
  background: rgba(245, 108, 108, 0.2);
  color: #f56c6c;
}

.network-driver.ipvlan {
  background: rgba(103, 194, 58, 0.2);
  color: #67c23a;
}

.network-driver.container {
  background: rgba(230, 162, 60, 0.2);
  color: #e6a23c;
}

.network-driver.other {
  background: rgba(245, 108, 108, 0.2);
  color: #f56c6c;
}

/* 创建网络对话框样式 */
.label-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}

.label-key {
  flex: 1;
}

.label-value {
  flex: 2;
}

.label-item .el-button {
  flex-shrink: 0;
}

/* 驱动信息提示框样式 */
.driver-info-box {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  margin: 16px 0;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.driver-info-box.info-type {
  border-left: 4px solid #409eff;
}

.driver-info-box.info-type i {
  color: #409eff;
  font-size: 18px;
  margin-top: 2px;
}

.driver-info-box.warning-type {
  border-left: 4px solid #e6a23c;
}

.driver-info-box.warning-type i {
  color: #e6a23c;
  font-size: 18px;
  margin-top: 2px;
}

.info-content {
  flex: 1;
}

.info-title {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 4px;
  color: #ffffff;
}

.info-desc {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.4;
}

/* 网络详情对话框样式 */
.network-detail {
  color: #ffffff;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  color: #ffffff;
  font-size: 16px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.detail-section h4 i {
  margin-right: 8px;
  color: #409eff;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.detail-item label {
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
  min-width: 100px;
  margin-right: 12px;
}

.detail-item span {
  color: rgba(255, 255, 255, 0.8);
}

.network-id, .container-id, .endpoint-id {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  background: rgba(255, 255, 255, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
}

.mac-address {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.option-key {
  font-weight: 600;
  color: #409eff;
  min-width: 200px;
  margin-right: 12px;
}

.option-value {
  color: rgba(255, 255, 255, 0.8);
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

/* 详情对话框样式 */
.inspect-dialog {
  --el-dialog-bg-color: rgba(26, 26, 26, 0.95);
  --el-dialog-border-radius: 12px;
}

.inspect-dialog .el-dialog__header {
  padding: 0;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
}

.inspect-dialog .el-dialog__body {
  padding: 0;
  background: #0a0a0a;
}

.inspect-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: rgba(26, 26, 26, 0.95);
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
}

.inspect-title {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #a4f4ba;
  font-size: 16px;
  font-weight: 500;
}

.inspect-icon {
  color: #a4f4ba;
  font-size: 18px;
}

.inspect-controls {
  display: flex;
  gap: 8px;
}

.inspect-content {
  height: 70vh;
  overflow: auto;
  background: #0a0a0a;
  padding: 0;
}

.inspect-pre {
  margin: 0;
  padding: 20px;
  background: #0a0a0a;
  color: #e6e6e6;
  font-family: 'Courier New', Monaco, monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
  border: none;
  outline: none;
}

.inspect-content::-webkit-scrollbar {
  width: 8px;
}

.inspect-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.inspect-content::-webkit-scrollbar-thumb {
  background: rgba(164, 244, 186, 0.3);
  border-radius: 4px;
}

.inspect-content::-webkit-scrollbar-thumb:hover {
  background: rgba(164, 244, 186, 0.5);
}

/* 连接容器对话框样式 */
.container-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.container-info i {
  color: #a4f4ba;
}
</style>
